/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package biz;

import da.AccountJpaController;
import da.exceptions.PreexistingEntityException;
import da.exceptions.RollbackFailureException;
import entities.Account;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import javax.transaction.UserTransaction;

/**
 *
 * @author TungGreen
 */
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class LoginProgess {

    @Resource
    private UserTransaction utx;
    @PersistenceUnit(unitName = "ProjectSem4PU")
    private EntityManagerFactory emf = null;
    private AccountJpaController jpa;

    public AccountJpaController getJpa() {
        if (jpa == null) {
            jpa = new AccountJpaController(utx, emf);
        }
        return jpa;
    }
    /**
     * 
     * Function get information of a Account
     * @param userName (username of this account)
     * @return 
     */
    public Account getUser(String userName) {
        String query = "SELECT a FROM Account a WHERE a.userName = :userName";
        TypedQuery<Account> tq = emf.createEntityManager().createQuery(query, Account.class);
        tq.setParameter("userName", userName);
        try {
            return tq.getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 
     * Function create Account 
     * 
     */
    public void createUser(Account account) throws PreexistingEntityException, RollbackFailureException, Exception {
        getJpa().create(account);
    }
    /**
     * 
     * Function get all Technician (Account with roleId =2)
     * @return 
     */
    public List<Account> getListTechnical() {
        List<Account> listTechnical = emf.createEntityManager().createQuery("SELECT c FROM Account c WHERE c.roleId.id = " + 2, Account.class).getResultList();
        return listTechnical;
    }
}
